package cn.lee.cplibrary.widget.recycler.decoration;

import android.graphics.Rect;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


/**
 * RecyclerView 线性布局（LinearLayoutManager）
 * HORIZONTAL: 设置横向列间距（距离父布局左右间距、item左右间距）
 * VERTICAL:设置纵向行间距（距离父布局上下间距、item上下间距）
 * Create by ChrisLee on 2021-09-14
 */
public class LinearSpacingDecoration extends RecyclerView.ItemDecoration {

    private int margin; //第1（列/行）距（左/上）边、最后一（列/行）距（右/下）边的距离
    private int itemSpacing; //item的列间隔（去掉首尾列）


    public LinearSpacingDecoration(int margin, int itemSpacing) {
        this.margin = margin;
        this.itemSpacing = itemSpacing;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view); //item position
        LinearLayoutManager layoutManager = (LinearLayoutManager) parent.getLayoutManager();
         if (layoutManager.getOrientation() == LinearLayoutManager.HORIZONTAL) {//横向，列间距
            if (position == 0) {//第一列
                outRect.left = margin;
                outRect.right = itemSpacing / 2;
            } else if (position == getChildCount(parent) - 1) {//最后一列
                outRect.left = itemSpacing / 2;
                outRect.right = margin;
            } else {
                outRect.left = itemSpacing / 2;
                outRect.right = itemSpacing / 2;
            }
        } else if (layoutManager.getOrientation() == LinearLayoutManager.VERTICAL) {//纵向，行间距
            //行间距
            if (position == 0) {//第一行
                outRect.top = margin;
                outRect.bottom = itemSpacing / 2;
            } else if (position == getChildCount(parent) - 1) {//最后一行
                outRect.top = itemSpacing / 2;
                outRect.bottom = margin;
            } else {
                outRect.top = itemSpacing / 2;
                outRect.bottom = itemSpacing / 2;
            }
        }
    }

    /**
     * 获取总Item数量
     *
     * @param parent
     * @return
     */
    private int getChildCount(RecyclerView parent) {
        int childCount = parent.getAdapter().getItemCount();
        return childCount;
    }

    public void setMargin(int margin) {
        this.margin = margin;
    }

    public void setItemSpacing(int itemSpacing) {
        this.itemSpacing = itemSpacing;
    }

}
